<template>
	<div class="map-dialog">
		<div class="car-list">
			<div class="tab-title">
				<span class="name" :class="{active:activeTab=='car'}" @click="activeTab='car'">车辆</span>
				<span class="name" :class="{active:activeTab=='person'}" @click="activeTab='person'">人员</span>
				<span class="name" :class="{active:activeTab=='warning'}" @click="activeTab='warning'">预警</span>
			</div>
			<el-input class="search" v-model="searchText">
				<span slot="suffix" class="el-icon-search"></span>
			</el-input>
			<div class="tab-body">
				<el-table id="car" v-show="activeTab=='car'" 	:data="carList.data" v-loading="loading" element-loading-text="正在连接GPS设备,请稍后..." stripe :height="tbHeight">
					<el-table-column prop="properties.vehiclecode"	label="车牌号"	>
						<span  slot-scope="scope" :title="scope.row.properties.vehiclecode">{{scope.row.properties.vehiclecode}}</span>
					</el-table-column>
					<el-table-column prop="properties.vehiclename"	label="车辆名称"	>
						<span  slot-scope="scope" :title="scope.row.properties.vehiclename">{{scope.row.properties.vehiclename}}</span>
					</el-table-column>
					<el-table-column	prop="properties.Speed"	label="当前车速(km/h)" width="150"></el-table-column>
					<el-table-column		label="操作"	width="50" align="center">
						<template slot-scope="scope">
							<i class="icon el-icon-location-outline" @click="car_handleClick(scope.row)" title="定位"></i>
						</template>
					</el-table-column>
				</el-table>
				<el-table id="person" v-show="activeTab=='person'" 	:data="personList.data" stripe  :height="tbHeight">
					<el-table-column prop="operatorName"	label="姓名">
						<span  slot-scope="scope" :title="scope.row.operatorName">{{scope.row.operatorName}}</span>
					</el-table-column>
					<el-table-column prop="typeName"	label="任务类型"></el-table-column>
					<el-table-column prop="status"	label="状态">
						<span slot-scope="scope">
							<span v-if="scope.row.status==0">未下发</span>
							<span v-else-if="scope.row.status==1">已下发</span>
							<span v-else>已完成</span>
							<!-- {{scope.status===0?'未下发':(scope.status==1? '已下发':'已完成')}} -->
						</span>
					</el-table-column>
					<el-table-column	 label="操作"	width="50" align="center">
						<template slot-scope="scope">
							<i class="icon el-icon-location-outline" @click="per_handleClick(scope.row)" title="定位"></i>
						</template>
					</el-table-column>
				</el-table>
				<el-table id="warning"   v-show="activeTab=='warning'" 	:data="warningList.data" stripe  :height="tbHeight">
					<el-table-column prop="gpsDeviceCode"	label="车牌号"	>
						<span  slot-scope="scope" :title="scope.row.vehicleCode">{{scope.row.vehicleCode}}</span>
					</el-table-column>
					<el-table-column	prop="vehicleCode"	label="车辆名称">
						<span  slot-scope="scope" :title="scope.row.vehicleName">{{scope.row.vehicleName}}</span>
					</el-table-column>
					<el-table-column	prop="createTime"	label="超出时间"	>
						<span  slot-scope="scope" :title="scope.row.createTime">{{scope.row.createTime}}</span>
					</el-table-column>
					<el-table-column		label="操作"	width="50" align="center">
						<template slot-scope="scope">
							<i class="icon el-icon-location-outline" @click="war_handleClick(scope.row)" title="定位"></i>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<el-pagination
				ref="elp"
				v-show="activeTab!='car'"
				layout="prev, pager, next"
			    :current-page="currentList.current"
			    :page-size="currentList.size"
			    :total="currentList.total"
			    @current-change="switchPage"
			    @prev-click="switchPage"
			    @next-click="switchPage"
			></el-pagination>
			<i class="corner top-left"></i>
			<i class="corner top-right"></i>
			<i class="corner bottom-left"></i>
			<i class="corner bottom-right"></i>
			<span class="clock">{{clock}}</span>
		</div>
		<locu-query ref="locusQuery" v-show="querDialog" :current-imei="checkImei" :start-time="startTime"></locu-query>
	</div>
</template>
<script>
import temp from "../../assets/json/temp.json";
import temp_per from "../../assets/json/temp_per.json";
import io from 'socket.io-client'
import LocuQuery from './locuQuery'
import gpsTransformation from '../../assets/js/map/gpsTransformation'
export default {
	components:{
		LocuQuery
	},
	mixins:[gpsTransformation],
    data() {
      return {
		loading: true,
		searchText:"",
		activeTab:"car",
		carList:{
			current:1,
			size:30,
			total:5,
			data:[]
		},
		personList:{
			current:1,
			size:30,
			total:5,
			data:[]
		},
		warningList:{
			current:1,
			size:30,
			total:5,
			data:[]
		},

		//currentList:{},//当前显示的列表
		car_layer: null,
		per_layer:null,
		map: null,
		LocateType: {
			'0':'未知',
			'1':'GPS',
			'2':'基站定位',
			'4':'北斗定位',
			'5':'GPS和北斗定位',
			'8':'格洛纳斯'
		},
		  checkImei:"",
		  startTime:"",
		  querDialog:false,
		  per_track_layer:null,
		  waring_layer:null,
		  clock:10,//倒计时
		  tbHeight:"",//
		  interval:null,
      }
	},
	watch:{
		activeTab(vv){
			// if(vv=='car'){
			// 	this.currentList=this.carList
			// }else if(vv=='person'){
			// 	this.currentList=this.personList
			// }else{
			// 	this.currentList=this.warningList
			// }
			this.setTableHeight()
			this.querDialog=false;
		},
		searchText(newVal,oldVal){
			if(this.activeTab=='car'){
				//this.get()
			}else if(this.activeTab=='person'){
				this.getPatrolPpsition(1);
			}else{
				this.gpsElectronicFenceWarn(1);
			}
		}
	},
	computed: {
		currentList() {
			var curlist={}
			if(this.activeTab=='car'){
				curlist=this.carList
			}else if(this.activeTab=='person'){
				curlist=this.personList
			}else{
				curlist=this.warningList
			}
			return curlist;
		}
	},

	methods:{
		switchPage(prm){
			if(this.activeTab=='car'){
				//this.get()
			}else if(this.activeTab=='person'){
				this.getPatrolPpsition(prm)
			}else{
				this.gpsElectronicFenceWarn(prm)
			}
		},
		queryClose(){
			this.$refs.locusQuery.clear();
		},
		initWebSocket () {
			// 连接错误
			this.websocket.onerror = this.setErrorMessage

			// 连接成功
			this.websocket.onopen = this.setOnopenMessage

			// 收到消息的回调
			this.websocket.onmessage = this.setOnmessageMessage

			// 连接关闭的回调
			this.websocket.onclose = this.setOncloseMessage

			this.websocket.send = this.setSendMessage

			// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
			window.onbeforeunload = this.onbeforeunload
		},
		setErrorMessage () {
			console.log('WebSocket连接发生错误   状态码：' + this.websocket.readyState)
		},
		setOnopenMessage () {
			console.log('WebSocket连接成功    状态码：' + this.websocket.readyState)
		},
		setOnmessageMessage (event) {
			// 根据服务器推送的消息做自己的业务处理
			// console.log('服务端返回：' + event.data);
			if (event.isTrusted) {
				var data = JSON.parse(event.data);
				if(this.searchText){
					var searchText = this.searchText;
					var features = data.features,filterF = [];
					for(var i = 0;i < features.length;i++){
						if(features[i].properties.vehiclecode.indexOf(searchText) != -1){
							filterF.push(features[i])
						}
					}
                   data.features = filterF;
				}
				this.carList.data = this.showCarGeojson(data);
				this.gpsElectronicFenceWarn()
			} else {
				console.log("服务器消息推送失败")
			}
			this.loading = false;

		},

		//加载预警信息
		gpsElectronicFenceWarn(pageNum){
             var self = this;
			 var submitData={
			     current:typeof pageNum=='number' ? pageNum : this.warningList.current,
			     size:this.warningList.size,
				 vehicleCode:this.searchText,
			 };
			this.$http.gpsElectronicFenceWarn(submitData)
			.then(res=>{
				var result = res.data.data;
				this.warningList.data = result.records;
				this.warningList.total = result.total;
				this.warningList.current = result.current;
			}).catch(err => {
				throw (err);
			})
		},
		setOncloseMessage () {
			console.log('WebSocket连接关闭    状态码：' + this.websocket.readyState)
		},
		setSendMessage(message){
			this.websocket.send(message);
		},
		onbeforeunload () {
			this.closeWebSocket()
		},
		closeWebSocket () {
			this.websocket.close()
		},
		init(){
			this.map = window.map;
           this.getPatrolPpsition();
		},

		//加载人员信息
		getPatrolPpsition(pageNum){
			var self = this;
			var submitData={
			    current:typeof pageNum=='number' ? pageNum : this.personList.current,
			    size:this.personList.size,
				search:this.searchText,
			};
          this.$http.getPatrolPpsition(submitData)
		  .then(res=>{
            var result = res.data.data;
			  this.personList.data=result.records;
			  this.personList.total= result.total;
			  this.personList.current= result.current;
			  self.showPerGeojson(result.records);
		  }).catch( err=>{
		  	throw (err);
		  });
		},
		car_handleClick(row) {
			if(this.querDialog){
				this.querDialog = false;
				this.$refs.locusQuery.clear();
			}
			var leaflet_id = row.properties.leaflet_id;
			// console.log(row)
			if (leaflet_id && this.car_layer.getLayer(leaflet_id)) {
				let marker = this.car_layer.getLayer(leaflet_id);
				marker.togglePopup();
				window.map.flyTo(marker.getLatLng());
			} else{
				console.log("找不到对象")
			}
		},
		per_handleClick(row) {
			if(!(row.lat && row.lng)){
				this.$message.info("没有巡查，暂无轨迹！！！");
				return;

			}
			var leaflet_id = row.id;
			// console.log(row)
			var layers = this.per_layer._layers;
			var flag = false;
			for(var key in layers){
              if(leaflet_id == layers[key].feature.properties.id){
				  layers[key].togglePopup();
				  window.map.flyTo(layers[key].getLatLng());
				  flag = true;
				  break;
			  }
			}
			if(!flag){
				console.log("找不到对象")
			}
		},

		//加载地图数据
		showCarGeojson(geoJSON){
			var car_up = L.icon({
				iconUrl: require("../../assets/images/map/car_up.png"),
				iconSize: [36, 36]
			});

			var cloffline = L.icon({
				iconUrl: require("../../assets/images/map/cloffline.png"),
				iconSize: [36, 36]
			});

			var map = window.map;
			var self = this;
			if (this.car_layer) {
				map.removeLayer(this.car_layer);
			}

			this.car_layer = L.geoJSON(geoJSON, {
				pointToLayer: function(geoJsonPoint, latlng) {
					let properties = geoJsonPoint.properties;
					let header=`
						<div class=header>
							<span class='iconfont icon-cheliang'>车辆信息</span>
							<i class='iconfont icon-guiji' title=查看轨迹 onclick=window.getTrack(${properties.IMEI},${properties.starttime})></i>
						</div>
					`;
					let table = `<ul class=ul>`;
					table +=`<li class=li><span class=label>车牌号</span><span class=value>${properties.vehiclecode}</span></li>`;
					table +=`<li class=li><span class=label>车辆名称</span><span class=value>${properties.vehiclename}</span></li>`;
					table +=`<li class=li><span class=label>车辆类型</span><span class=value>${properties.type}</span></li>`;
					table +=`<li class=li><span class=label>当前车速</span><span class=value>${properties.Speed}</span></li>`;
					table +=`<li class=li><span class=label>车辆负责人</span><span class=value>${properties.responsible}</span></li>`;
					table +=`<li class=li><span class=label>设备编号</span><span class=value>${properties.IMEI}</span></li>`;
					table =table+"</ul>";
					let popuptHtml=header+table;
					let juge = properties.juge
					let marker = L.marker(latlng, { icon: (juge?car_up:cloffline) }).bindPopup(popuptHtml,{
						offset: L.point(0, 0)
					});
					marker.setRotationAngle(properties.Dir+90);
					return marker;
				}
			}).addTo(this.map);

			this.car_layer.eachLayer(function (item) {
				item.feature.properties.leaflet_id=item._leaflet_id
				return item
			});
			var geoJSON = this.car_layer.toGeoJSON();
			return geoJSON.features
		},
		/*
		* 获取设备历史轨迹
		* */
		getTrack(imei,startTime){
			this.startTime = startTime;
			this.checkImei = imei+"";
			this.querDialog = true;
		},
		getPerTrack(id){
			var self = this;
			var data = {
				taskId:id
			}
			this.$http.getTaskDetails(data).then(res => {
				var result = res.data.data;
				if(Array.isArray(result)){
                  var track = result.map(item=>{
						return [item.lat,item.lng]
					});
					this.showTrack(track);
				}else if(typeof result == 'object'){
					var fileUrl = result.filePath.replace(/^http:\/\/\d+\.\d+\.\d+\.\d+:\d{2,4}/,"")
					this.$http.downloadFile(fileUrl,{responseType:'json'})
							.then(res => {
								var data  = res.data;
								var path = data.map(item=>{
									return self.gcj02towgs84(item.lat, item.lng)
								});
								self.showTrack(path);
							}).catch((err) => {
							var data = err.data;
							var path = data.map(item => {
								return self.gcj02towgs84(item.lat, item.lng)
							});
							self.showTrack(path);
					})
				}else if(typeof result == 'string'){
					this.$message.info(result);
					return;
				}
			}).catch(err=>{
				throw (err);
			});
		},
		showTrack(track){
			var self = this;
			if(this.per_track_layer){
				this.per_track_layer.clearLayers();
			}else {
				this.per_track_layer = new L.layerGroup().addTo(window.map);
			}
			var polyline = L.polyline(track, {color: 'red'}).addTo(self.per_track_layer);
           // debugger
			//加载起止点坐标
			var startIcon = L.icon({
				iconUrl: require("../../assets/images/map/startPoint.png"),
				iconSize: [36, 36]
			});
			let startPoint = L.marker(track[0], { icon: startIcon}).bindPopup('起点',{
				offset: L.point(0, 0)
			}).addTo(this.per_track_layer);
			window.map.setView(track[0])
			window.map.setZoom(11)
			/*let endPoint = L.marker(track[track.length-1], { icon: endIcon}).bindPopup('终点',{
				offset: L.point(0, 0)
			}).addTo(this.per_track_layer);*/
		},
		showPerGeojson(list){
			var per_online = L.icon({
				iconUrl: require("../../assets/images/map/per_online.png"),
				iconSize: [32, 32]
			});

			var map = window.map;
			/*if(this.per_layer){
				this.per_layer.clearLayers();
			}else{
				this.per_layer = new L.layerGroup().addTo(window.map);
			}*/
			var geoJson = {
				"type": "FeatureCollection",
				features:[]
			}
			if(list && list.length > 0){
				for(var i = 0;i < list.length;i++){
					if(list[i].lng && list[i].lat){
						var point = this.gcj02towgs84(list[i].lat,list[i].lng);
						var feture = {
							"type": "Feature",
							"properties":list[i] ,
							"geometry": {
								"type": "Point",
								"coordinates": [point[1],point[0]]
							}
						}
						geoJson.features.push(feture);
					}
				}

			}
			this.per_layer = L.geoJSON(geoJson, {
				pointToLayer: function(geoJsonPoint, latlng) {
					let properties = geoJsonPoint.properties;
					let header=`
						<div class=header>
							<span class='iconfont icon-renyua'>人员信息</span>
							<i class='iconfont icon-guiji' title=查看轨迹 onclick=window.getPerTrack('${properties.id}')></i>
						</div>
					`;
					let table="<ul class=ul>";
						table +=`<li class=li><span class=label>任务标题</span><span class=value title="${properties.title}">${properties.title}</span></li>`;
						table +=`<li class=li><span class=label>任务类型</span><span class=value>${properties.typeName}</span></li>`;
						table +=`<li class=li><span class=label>巡查人员姓名</span><span class=value>${properties.operatorName}</span></li>`;
						// table +=`<li class=li><span class=label>巡查时间</span><span class=value  title="${properties.createTime}">${properties.createTime}</span></li>`;
						table +=`<li class=li><span class=label>巡查状态</span><span class=value>${properties.status==0?'未下发':(properties.status==1)?'已下发':'已完成'}</span></li>`;
					table += "</ul>";
					let popuptHtml=header + table;
					//let juge = properties.juge;
					let marker = L.marker(latlng, { icon: per_online}).bindPopup(popuptHtml,{
						offset: L.point(0, 0)
					});
					return marker;
				}
			}).addTo(this.map);

			/*this.per_layer.eachLayer(function (item) {
				item.feature.properties.leaflet_id = item._leaflet_id
				return item
			});*/
			var geoJSON = this.per_layer.toGeoJSON();
			return geoJSON.features
		},
		//预警信息
		war_handleClick(row){
			if(this.waring_layer){
				this.waring_layer.clearLayers();
			} else {
				this.waring_layer = new L.layerGroup().addTo(window.map)
			}
			if(row.pointsPosition){
				var point = row.pointsPosition.split(",");
				var war_online = L.icon({
					iconUrl: require("../../assets/images/map/point.png"),
					iconSize: [32, 32]
				});
				var layer = L.marker(point, { icon: war_online}).addTo(this.waring_layer);
				//layers[key].togglePopup();
				window.map.flyTo(layer.getLatLng());
			}
		},
		setTableHeight(obj){
			this.$nextTick(()=>{
				var el=document.querySelector(".tab-body");
				var footerH=this.$refs.elp.$el;
				setTimeout(()=>{
					this.tbHeight=el.offsetHeight ||"";
				},100)
			})
		},
	},
	mounted(){
		window.getTrack = this.getTrack;
		window.getPerTrack = this.getPerTrack;
		//WebSocket
		if ('WebSocket' in window) {
			this.websocket = new WebSocket(window.socketUrl + 'testNum');
			window.websocket = this.websocket;
			this.initWebSocket();
		} else {
			this.$message.warning("当前浏览器不支持websocket,因而无法查询车辆数据!")
		}

		this.interval=setInterval(()=>{
			if(--this.clock ==0){
				this.clock=10;
				this.getPatrolPpsition()
			}
		},1000)
	},
	beforeDestroy () {
	  this.onbeforeunload()
	  clearInterval(this.interval)
	},
  }
</script>
<style scoped="scoped" lang="scss">
	.map-dialog{
		position: absolute;
		z-index: 1111;
		top: 0;
		left:0;
		bottom: 0px;
	}
	.car-list{
		width:min-content;
		min-width:350px;
		min-height:200px;
		max-width:500px;
		display: flex;
		flex-direction: column;
		background-color: #01183F;
		position: absolute;
		top:10px;
		left:10px;
		bottom: 10px;
		padding:10px 20px;
		box-sizing: border-box;
		box-shadow: 0px 0px 10px 1px #2977A4 inset;
	}

	.tab-title{
		display: flex;
		position: relative;
		margin-bottom: 10px;
		padding-bottom: 10px;
		&:after{
			content: '';
			display: inline-block;
			width:100%;
			height:1px;
			background: linear-gradient(to right, #01183f, #157c82, #01183f);
			position: absolute;
			bottom: 0px;
			left: 0px;
		}
		.name{
			text-align: center;
			flex:1;
			cursor: default;
			color:#00C3D9;
			&:after{
				content: '';
				display: block;
				width:100%;
				height:3px;
				background-size: 100% 100%;
				position: relative;
				top: 4px;
			}
			&.active{
				&:after{
					background:url(~@/assets/images/home/active-tab.png) no-repeat  center ;
				}
			}

		}
	}

	.search{
		margin-bottom: 10px;
		/deep/ .el-input__inner{
			height: 30px;
			line-height: 300px;
			background-color: transparent;
			color: #00C3D9;
			border-radius: 20px;
			border-color:#02BDE5;
		}
		.el-icon-search{
			padding: 8px;
			color: #02BDE5;
		}
	}
	.tab-body{
		flex:1;
		overflow: hidden;
		/deep/ .el-table{
			height: 100%;
			overflow: auto;
			color: #97d3d8;
			background-color: transparent;
			&::before{
				height: 0px;
			}
			thead{
				color: #02D7E5;
			}
			tr,th{
				background-color: transparent;
				border-bottom: none;
			}
			td,th{
				padding:3px 0px;
				border-bottom: none;
				cursor: default;
			}
			.el-table__fixed-right::before,
			.el-table__fixed::before{
				background-color: transparent;
			}
			.el-table__empty-text{
				color: #497bd0;
			}
			.el-table__header tr{
				background: linear-gradient(to right, #01183f, #2977A4, #01183f);
			}
			&.el-table--striped {
				.el-table__body tr.el-table__row--striped{
					//background:linear-gradient(to right, #01183f, #2977a44a, #01183f);
					background-color: #002450;
					td{
						background-color: transparent;
					}
				}
			}
			.hover-row td{
				background-color: transparent;
			}
			tr:hover td{
				background-color: transparent;
			}
		}
	}

	/deep/ .el-tabs__item{
		padding-left: 20px !important;
	}

	.icon{
		padding:5px;
		cursor: pointer;
		&:hover{
			color:#16a3fa;
		}
	}

/deep/ .el-loading-mask{
	background: radial-gradient(circle ,rgb(0, 42, 113), transparent,transparent);
}

.corner{
	display: block;
	width:50px;
	height:50px;
	background: url(~@/assets/images/home/border.png) no-repeat;
	background-size: 100% 100%;
	position: absolute;
	&.top-left{
		top:0;
		left: 0;
	}
	&.top-right{
		top:0;
		right: 0;
		transform: rotateY(180deg);
	}
	&.bottom-left{
		bottom:0;
		left: 0;
		transform: rotateX(180deg);
	}
	&.bottom-right{
		right:0;
		bottom: 0;
		transform: rotateZ(180deg);
	}
}


/deep/ .el-pagination{
	margin: 0px;
	color: #42609c;
	z-index: 1;
	*{
		background-color: transparent !important;
	}
}

.clock{
	position: absolute;
	    top: 10px;
	    right: 10px;
	    display: inline-block;
	    color: #05e5ea;
	    width: 23px;
		height: 23px;
		box-shadow: 0px 0px 9px 0px #02d7e5 inset;
		border-radius: 50%;
		text-align: center;
		line-height: 23px;
}

.locusQuery{
	background-color: #01183F;
	position: fixed;
	left: 500px;
	top: 70px;
	min-height: 200px;
	max-height: 600px;
	padding: 10px;
	color: #fff;
	/deep/ .el-form{
		.el-form-item__label{
			color:#fff;
		}
		.el-input__inner{
			background-color: transparent;
			color: #fff;
		}
	}
}
</style>

